package com.cgl.service.imp;

import com.cgl.mapper.UserMapper;
import com.cgl.pojo.User;
import com.cgl.service.UserService;
import com.cgl.until.SHA256PasswordEncryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Random;
@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Boolean register(User user) {
        Random random = new Random();

        String id= random.ints(48, 57)
                .limit(16)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();//生成随机id
        user.setId(id);

        SHA256PasswordEncryption sha256PasswordEncryption = new SHA256PasswordEncryption();
        String password = sha256PasswordEncryption.hashPassword(user.getPassword());
        user.setPassword(password);

        user.setPassword1("null");
        user.setImagePath("null");
        user.setStatus("0"); //0：已注册
        user.setRole("0"); // 0：普通用户
        user.setCreatedTime(LocalDate.now());
        user.setUpdatedTime(LocalDate.now());

        int result = userMapper.addUser(user);
        if (result == 1){
            return true;
        }
        return false;
    }

    @Override
    public User login(User user) {

        SHA256PasswordEncryption sha256PasswordEncryption = new SHA256PasswordEncryption();
        String password = sha256PasswordEncryption.hashPassword(user.getPassword());
        user.setPassword(password);

        User user1 = userMapper.selectUserByEmailAndPassword(user);
        if (user1 != null){
            user1.setPassword("null");
            user1.setPassword1("null");
            return user1;
        }else {
            return null;
        }
    }

    @Override
    public Boolean isExist(String email) {
        return null;
    }

    @Override
    public User getUserById(String id) {
        User user = userMapper.selectUserById(id);
        return user;
    }
}
